//
//  BuyVIPViewController.m
//  Hxcsfw
//
//  Created by 企友软mac on 2018/1/15.
//  Copyright © 2018年 企友软mac. All rights reserved.
//

#import "BuyVIPViewController.h"
#import "InvoiceInfoViewController.h"
#import "UIImageView+WebCache.h"
#import "IAPHelper.h"
#import "IAPProduct.h"

@interface BuyVIPViewController ()<UIAlertViewDelegate> {
    UIView *bgView;
    UIView *payView;
    IAPProduct *product;
}

@property (nonatomic, strong) IAPHelper  *m_iapHelper;
@property (nonatomic, strong) NSMutableArray *m_productArray;

@property (weak, nonatomic) IBOutlet UIImageView *imgView;
@property (weak, nonatomic) IBOutlet UILabel *lbTitle;
@property (weak, nonatomic) IBOutlet UILabel *lbCion;
@property (weak, nonatomic) IBOutlet UILabel *lbRealityCion;
@property (weak, nonatomic) IBOutlet UILabel *lbNote;
@property (weak, nonatomic) IBOutlet UIButton *btnSubmit;
@property (weak, nonatomic) IBOutlet UIButton *btnNote;
@property (weak, nonatomic) IBOutlet UILabel *lbState;

@end

@implementation BuyVIPViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if ([WShareUtil sharedData].isHaveInvoice) {
        self.lbNote.text = @"电子发票";
    }else {
        self.lbNote.text = @"不开发票";
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];

    if (self.vdModel) {
        self.lbTitle.text = self.vdModel.StrTitlestr;
        self.lbState.hidden = YES;
        [self.imgView sd_setImageWithURL:[NSURL URLWithString:self.vdModel.imgsrc] placeholderImage:[UIImage imageNamed:@"school_image.png"]];
        self.lbRealityCion.text = [NSString stringWithFormat:@"￥%@",self.vdModel.charged];
        self.lbCion.text = [NSString stringWithFormat:@"￥%@",self.vdModel.charged];
    }else {
        self.lbTitle.text = self.myOrderModel.KC_NAME;
        [self.imgView sd_setImageWithURL:[NSURL URLWithString:self.myOrderModel.PICURL] placeholderImage:[UIImage imageNamed:@"school_image.png"]];
        self.lbRealityCion.text = [NSString stringWithFormat:@"￥%@",self.myOrderModel.KC_PRICE];
        self.lbCion.text = [NSString stringWithFormat:@"￥%@",self.myOrderModel.KC_PRICE];
        if ([self.myOrderModel.KPLXMC isEqualToString:@"不开票"]) {
            self.lbNote.text = @"不开发票";
            [WShareUtil sharedData].isHaveInvoice = NO;
        } else {
            self.lbNote.text = @"电子发票";
            [WShareUtil sharedData].isHaveInvoice = YES;
        }

        if ([[self.myOrderModel ZFJG] isEqualToString:@"0"]) {
            self.btnSubmit.hidden = NO;
            [self.lbState setTextColor:[UIColor redColor]];
            self.lbState.text = @"未支付";

        } else {
            self.btnSubmit.hidden = YES;
            self.btnNote.hidden = YES;
            [self.lbState setTextColor:WRGBColor(54, 157, 46)];
            self.lbState.text = @"已支付";
        }
    }
    [self loadData];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySuccess) name:@"PaySuccess" object:nil];//注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payFlase) name:@"PayFlase" object:nil];//注册通知
}

- (void)paySuccess {
    [self removePayView];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)payFlase {
    [self removePayView];
}

- (IBAction)invoiceInfoBtnClick:(UIButton *)sender {

    if (sender.tag == 1000) {
        InvoiceInfoViewController *invoiceInfoVc = [[InvoiceInfoViewController alloc] init];
        invoiceInfoVc.title = @"发票信息";
        invoiceInfoVc.productId = self.vdModel.ID;
        [self.navigationController pushViewController:invoiceInfoVc animated:YES];
    } else {
        WLog(@"提交订单");
        [self createPayView];
//        if (self.vdModel) {
//            [self reportSubmitInvoiceInfo];
//        } else {
//            [self reportMyOrderSubmitInvoiceInfo];
//        }
    }
}

- (void)createPayView {
    bgView = [[UIView alloc] initWithFrame:self.view.bounds];
    bgView.backgroundColor = WRGBAColor(0, 0, 0, 0.5);
    [self.view addSubview:bgView];

    payView = [[UIView alloc] initWithFrame:CGRectMake(0, WSCREENH_HEIGHT - 180, WSCREENH_WIDTH, 180)];
    payView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:payView];

    UILabel *lbTit = [[UILabel alloc] initWithFrame:CGRectMake((WSCREENH_WIDTH - 80) * 0.5, 5, 80, 44)];
    lbTit.text = @"付款";
    lbTit.textAlignment = NSTextAlignmentCenter;
    [lbTit setTextColor:[UIColor blackColor]];

    //分割线
    UILabel *lbLine = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, WSCREENH_WIDTH, 1)];
    lbLine.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
    
    UIButton *btnClose = [[UIButton alloc] initWithFrame:CGRectMake(WSCREENH_WIDTH - 30, 18, 15, 15)];
    [btnClose setImage:[UIImage imageNamed:@"GB.png"] forState:UIControlStateNormal];
    [btnClose addTarget:self action:@selector(removePayView) forControlEvents:UIControlEventTouchUpInside];

    UILabel *lbPay = [[UILabel alloc] initWithFrame:CGRectMake((WSCREENH_WIDTH - 50) * 0.5 - 25, 60, 50, 44)];
    lbPay.text = @"支付";
    lbPay.textAlignment = NSTextAlignmentCenter;
    [lbPay setTextColor:[UIColor blackColor]];

    UILabel *lbMoney = [[UILabel alloc] initWithFrame:CGRectMake((WSCREENH_WIDTH - 50) * 0.5 + 25, 60, 50, 44)];
    if (self.vdModel) {
        lbMoney.text = [NSString stringWithFormat:@"￥%@",self.vdModel.charged];
    }else {
        lbMoney.text = [NSString stringWithFormat:@"￥%@",self.myOrderModel.KC_PRICE];
    }
    lbMoney.textAlignment = NSTextAlignmentCenter;
    [lbMoney setTextColor:[UIColor colorWithRed:0.95 green:0.44 blue:0.23 alpha:1]];

    UIButton *btnPay = [[UIButton alloc] initWithFrame:CGRectMake(20, 110, WSCREENH_WIDTH - 40, 45)];
    btnPay.layer.masksToBounds = YES;
    btnPay.layer.cornerRadius = 5;
    btnPay.backgroundColor = [UIColor colorWithRed:0.95 green:0.29 blue:0 alpha:1];
    [btnPay setTitle:@"确认支付" forState:UIControlStateNormal];
    [btnPay setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

    [btnPay addTarget:self action:@selector(btnPayClick) forControlEvents:UIControlEventTouchUpInside];

    [payView addSubview:lbTit];
    [payView addSubview:lbLine];
    [payView addSubview:btnClose];
    [payView addSubview:lbPay];
    [payView addSubview:lbMoney];
    [payView addSubview:btnPay];
}

- (void)removePayView {
    [payView removeFromSuperview];
    [bgView removeFromSuperview];
}

- (void)btnPayClick {

    NSString *strCharged;
    NSString *strCourseId;
    if (self.vdModel) {
        strCharged = self.vdModel.charged;
        strCourseId = self.vdModel.ID;
    }else {
        strCharged = self.myOrderModel.KC_PRICE;
        strCourseId = self.myOrderModel.ID;
    }

    [self requestBuyCourse:strCourseId];

    [WShareUtil sharedData].isMember = NO;

    [WShareUtil sharedData].isShowWait = YES;
    [WShareUtil showWait:YES frame:CGRectMake(0, 32, WSCREENH_WIDTH, WSCREENH_HEIGHT)];
}

- (void)requestBuyCourse:(NSString *)strCourseId {

    NSString *username;
    NSString *nologinuser = [WShareUtil getUUID];

    NSDictionary *parametersDict;
    if ([WShareUtil sharedData].dicSession) {
        username = [WShareUtil sharedData].dicSession[@"nsrsbh"];
        if (username == nil) {
            username = @"";
        }
        parametersDict = @{@"content":@{@"apptype":@"ios",@"dto":@{@"from":@"hxjt",@"productId":strCourseId},@"revert":@"remaining",@"username":username},@"mode":@"native",@"service":@"order"};
    }else {
        parametersDict = @{@"content":@{@"apptype":@"ios",@"dto":@{@"from":@"hxjt",@"productId":strCourseId},@"revert":@"remaining",@"nologinuser":nologinuser},@"mode":@"native",@"service":@"order"};
    }

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];

        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];

        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if ([successStr isEqualToString:@"true"]) {

            if (![WShareUtil sharedData].isWDDD) {
            
                [WShareUtil sharedData].dicBuySymbol = @{@"boughten":@"1",@"chosen":@"0",@"id":strCourseId};
            }
            [WShareUtil showAlert:@"温馨提示" message:@"购买成功"];
            
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [WShareUtil showAlert:@"温馨提示" message:returnDic[@"errorInfo"]];
        }

        [WShareUtil sharedData].isWDDD = NO;

        [WShareUtil showWait:NO frame:CGRectZero];

    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
//        [self reportSubmitInvoiceInfo];
        [IAPHelper sharedData];

        self.m_iapHelper = [IAPHelper new];
        self.m_iapHelper.m_buyType = product.m_buyType;

        [self.m_iapHelper requestProductData];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self removePayView];
}

// 课程详情中提交订单
- (void)reportSubmitInvoiceInfo {

    //        parametersDict = @{@"mode":@"native",@"service":@"order",@"content":@{@"revert":@"create",@"username":@"",@"dto":@{@"EMAIL":self.txtMailbox.text,@"KPLX":@"3",@"KPMC":self.txtTicketName.text,@"KPSH":self.txtNum.text,@"LXDH":self.txtPhone.text,@"LXR":self.txtName.text,@"productId":@"",@"productNum":@"2",@"备注":self.txtExplain.text}}};

    NSString *strId;
    NSDictionary *dtoDic;
    if ([WShareUtil sharedData].dicMinvoice) {
        dtoDic = [[WShareUtil sharedData].dicMinvoice copy];
    } else {
        if (![WShareUtil strNilOrEmpty:self.vdModel.ID]) {
            strId = self.vdModel.ID;
        } else if (![WShareUtil strNilOrEmpty:self.myOrderModel.ID]){
            strId = self.myOrderModel.ID;
        } else {
            strId = @"";
        }
        [WShareUtil sharedData].productId = strId;
        dtoDic = @{@"EMAIL":@"",@"KPLX":@"4",@"KPMC":@"",@"KPSH":@"",@"LXDH":@"",@"LXR":@"",@"productId":strId,@"productNum":@"1",@"BZ":@""};
    }

    NSString *username;
    NSString *nologinuser = [WShareUtil getUUID];

    NSDictionary *parametersDict;
    if ([WShareUtil sharedData].dicSession) {
        username = [WShareUtil sharedData].dicSession[@"nsrsbh"];
        if (username == nil) {
            username = @"";
        }
        parametersDict = @{@"mode":@"native",@"service":@"order",@"content":@{@"revert":@"create",@"username":username,@"apptype":@"ios",@"dto":dtoDic}};
    }else {
        parametersDict = @{@"mode":@"native",@"service":@"order",@"content":@{@"revert":@"create",@"apptype":@"ios",@"nologinuser":nologinuser,@"dto":dtoDic}};
    }

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];

        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
       
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if ([successStr isEqualToString:@"true"]) {
            [WShareUtil sharedData].dicOrder = returnDic;
            [self createPayView];
        } else {
            [WShareUtil showAlert:@"温馨提示" message:returnDic[@"errorInfo"]];
        }

    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
}

- (void)loadData {
    IAPProduct *product1 = [IAPProduct new];
    product1.m_buyType = ID_Coin1;

    IAPProduct *product2 = [IAPProduct new];
    product2.m_buyType = ID_Coin2;

    IAPProduct *product3 = [IAPProduct new];
    product3.m_buyType = ID_Coin3;

    IAPProduct *product4 = [IAPProduct new];
    product4.m_buyType = ID_Coin4;

    IAPProduct *product5 = [IAPProduct new];
    product5.m_buyType = ID_Coin5;

    IAPProduct *product6 = [IAPProduct new];
    product6.m_buyType = ID_Coin6;

    IAPProduct *product7 = [IAPProduct new];
    product7.m_buyType = ID_Coin7;

    IAPProduct *product8 = [IAPProduct new];
    product8.m_buyType = ID_Coin8;

    IAPProduct *product9 = [IAPProduct new];
    product9.m_buyType = ID_Coin9;

    IAPProduct *product10 = [IAPProduct new];
    product10.m_buyType = ID_Coin10;

    IAPProduct *product11 = [IAPProduct new];
    product11.m_buyType = ID_Coin11;

    IAPProduct *product12 = [IAPProduct new];
    product12.m_buyType = ID_Coin12;

    IAPProduct *product13 = [IAPProduct new];
    product13.m_buyType = ID_Coin13;

    IAPProduct *product14 = [IAPProduct new];
    product14.m_buyType = ID_Coin14;

    IAPProduct *product15 = [IAPProduct new];
    product15.m_buyType = ID_Coin15;

    IAPProduct *product16 = [IAPProduct new];
    product16.m_buyType = ID_Coin16;

    IAPProduct *product17 = [IAPProduct new];
    product17.m_buyType = ID_Coin17;

    IAPProduct *product18 = [IAPProduct new];
    product18.m_buyType = ID_Coin18;

    IAPProduct *product19 = [IAPProduct new];
    product19.m_buyType = ID_Coin19;

    self.m_productArray = [NSMutableArray arrayWithObjects:product1,product2,product3,product4,product5,product6,product7,product8,product9,product10,product11,product12,product13,product14,product15,product16,product17,product18,product19,nil];
}

// 我的订单中提交订单
- (void)reportMyOrderSubmitInvoiceInfo {
    NSDictionary *dtoDic;
    NSDictionary *parametersDict;
    NSString *username;
    if ([WShareUtil sharedData].dicSession) {
        username = [WShareUtil sharedData].dicSession[@"nsrsbh"];
        if (username == nil) {
            username = @"";
        }

        NSString *strId;
        if (![WShareUtil strNilOrEmpty:self.myOrderModel.ID]){
            strId = self.myOrderModel.ID;
        } else {
            strId = @"";
        }

        NSString *orderNo;
        if (![WShareUtil strNilOrEmpty:self.myOrderModel.ORDERNO]){
            orderNo = self.myOrderModel.ORDERNO;
        } else {
            orderNo = @"";
        }
        [WShareUtil sharedData].productId = strId;
        dtoDic = @{@"cat":@"0",@"orderId":strId,@"orderNo":orderNo};
        parametersDict = @{@"mode":@"native",@"service":@"order",@"content":@{@"apptype":@"ios",@"revert":@"payorder",@"username":username,@"dto":dtoDic}};
    }

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];

    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];

        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
       
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if ([successStr isEqualToString:@"true"]) {
            [WShareUtil sharedData].dicOrder = returnDic;
            [self createPayView];
        } else {
            [WShareUtil showAlert:@"温馨提示" message:returnDic[@"errorInfo"]];
        }
    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
}

@end
